package com.ny.controller;

import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.until.JwtUtil;
import com.ny.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    private final Map<String, Object> map = new HashMap<>();

    // 登录接口：POST /login
    @PostMapping("/login")
    public Result login(String username, String password) {
        User user = userService.findUser(username, password);
        if (user != null) {
            String token = jwtUtil.generateToken(user.getUsername());// 生成Token
            jwtUtil.storeToken(token, user.getUsername());// 存储到Redis
            map.clear();
            map.put("token", token);// Token存入返回结果
            map.put("users", user);// 用户信息存入返回结果
            return Result.success(map);// 返回成功结果
        } else {
            return Result.error("用户名和密码错误");// 返回错误信息
        }
    }

    // 登出接口：POST /logout
    //http://127.0.0.1:8081/logout
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        // 从请求头获取Token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return Result.error("未提供Token");
        }

        // 从Token中获取用户名
        String username = jwtUtil.getUsernameFromToken(token);

        // 从Redis中移除Token
        jwtUtil.removeToken(username);
        return Result.success("登出成功");
    }
}